package pers.qianyu.controller;

import io.swagger.annotations.*;
import lombok.extern.slf4j.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.*;
import pers.qianyu.domain.common.*;
import pers.qianyu.exception.*;
import pers.qianyu.service.*;

import javax.annotation.*;
import java.io.*;

/**
 * 文件服务
 *
 * @author mizzle rain
 * @date 2020-10-14 11:22
 */
@Api(value = "文件相关接口", protocols = "http,https")
@Slf4j
@RestController
@RequestMapping("/api/files")
public class FileController {
    @Resource(name = "localFileServiceImpl")
    private FileService fileService;

    @ApiOperation(value = "上传文件", notes = "上传文件到服务器")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "file",
                    value = "用户要上传的文件",
                    required = true,
                    paramType = "body",
                    dataType = "MultipartFile",
                    dataTypeClass = MultipartFile.class
            )
    })
    @PostMapping("upload")
    public HttpResult<String> upload(@RequestParam("file") MultipartFile multipartFile) {
        String fileName = multipartFile.getOriginalFilename();
        try {
            InputStream in = multipartFile.getInputStream();
            fileService.upload(in, fileName);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e.getMessage());
            throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_FAILURE, e);
        }
        return HttpResult.okWithData(fileName);
    }
}
